import { getUserInfoAPI, loginAPI } from '@/api/user'
import router, { constantRoutes, resetRouter } from '@/router'
import { getToken, removeToken, setToken } from '@/utils/auth'
import { Message } from 'element-ui'

const state = {
  token: getToken(),
  userInfo: {},
  // 2. 定义路由数据
  routes: constantRoutes
}

const mutations = {
  saveToken(state, payload) {
    state.token = payload
  },
  saveUserInfo(state, payload) {
    state.userInfo = payload
  },
  // 3. 定义mutation更新路由
  setRoutes(state, payload) {
    state.routes = [...constantRoutes, ...payload]
  }
}

const actions = {
  async loginAction(store, payload) {
    const res = await loginAPI(payload)

    store.commit('saveToken', res)
    setToken(res)
    router.push('/')
    Message({ message: '登录成功', type: 'success' })
  },

  async getUserInfoAction(store) {
    const res = await getUserInfoAPI()
    store.commit('saveUserInfo', res)
  },

  logoutAction(store) {
    store.commit('saveToken', '') // 清空vuex中token
    removeToken() // 清空cookie中的token
    store.commit('saveUserInfo', {}) // 清空vuex中userInfo
    router.push('/login') // 跳转到登录
    // 1.
    resetRouter() // 重置路由
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

